package com.example.samchat;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

	String xml;
	 TextView txtResult;
	 EditText myEditText;
	 ArrayList<String> todoItems;
	 ArrayAdapter<String> aa;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		myEditText = (EditText)findViewById(R.id.editText1);
		ListView myListView = (ListView)findViewById(R.id.listView1);
	        
	        Button btn = (Button)findViewById(R.id.button1);
	         todoItems  = new ArrayList<String>();
	        aa= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,todoItems);
	         
	         myListView.setAdapter(aa);
	       
//	        btn.setOnClickListener(new OnClickListener() {
//				@Override
//				public void onClick(View v) {
//	                       todoItems.add( myEditText.getText().toString());
//	                       aa.notifyDataSetChanged();
//	                       myEditText.setText("");
//	                     
//				}
//			});
	         handler1.sendEmptyMessage(0);
	       
	        
			
			/*	Send 버튼을 눌렀을 때 서버에 데이터를 보내고 받는다	*/
	        btn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					String sMessage = myEditText.getText().toString(); // 보내는 메시지를 받아옴
					String result = SendByHttp(sMessage); // 메시지를 서버에 보냄
					todoItems.add(result);
                    aa.notifyDataSetChanged();
				}
			});
		}
		
	     //서버에서 XML다운받아 파싱   
		public void downXml(){
			 StringBuffer sBuffer = new StringBuffer();
			  try {
			   String urlAddr = "http://godling2.cafe24.com/chat/index.php/room/msgs/id/1";
			   //위의 사이트에는 본인의 웹호스팅 주소나 서버 주소를 적으시고 뒤에 data.xml 넣으시길 바랍니다.
			   URL url = new URL(urlAddr);
			   HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			   if(conn != null) {
			    conn.setConnectTimeout(20000);
			    conn.setUseCaches(false);
			    if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			     InputStreamReader isr = new InputStreamReader(conn.getInputStream());
			     BufferedReader br = new BufferedReader(isr);
			     while(true) {
			      String line = br.readLine();
			      if(line == null) {
			       break;
			      }
			      sBuffer.append(line);
			     }
			     br.close();
			     conn.disconnect();
			    }
			   }
			   xml = sBuffer.toString();
			  } catch(Exception e) {
			   Log.e("다운로드 중 에러 발생", e.getMessage());
			  }
			  parse();
		}
		 public void parse() {
		  try {
		   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		   DocumentBuilder documentBuilder = factory.newDocumentBuilder();
		   InputStream is = new ByteArrayInputStream(xml.getBytes());
		   Document doc = documentBuilder.parse(is);
		   doc.getDocumentElement().normalize();
		   
		   NodeList headline_node_list = doc.getElementsByTagName("item");
		   String id = "", nic = "";
		   String msg = "";
		   
		   for(int i = 0;i<headline_node_list.getLength(); i++) {
		    Node headline_node = headline_node_list.item(i);
		    if(headline_node.getNodeType() == Node.ELEMENT_NODE) {
		     Element element = (Element) headline_node;
		     NodeList node_list = element.getElementsByTagName("id");
		     Node node = node_list.item(0);
		     id = node.getTextContent();
		    }
		    if(headline_node.getNodeType() == Node.ELEMENT_NODE) {
		     Element element = (Element) headline_node;
		     NodeList node_list = element.getElementsByTagName("nic");
		     Node node = node_list.item(0);
		     nic = node.getTextContent();
		    }
		    if(headline_node.getNodeType() == Node.ELEMENT_NODE) {
			     Element element = (Element) headline_node;
			     NodeList node_list = element.getElementsByTagName("msg");
			     Node node = node_list.item(0);
			     msg = node.getTextContent();
			    }
		    msg += (nic +" "+msg+"\n");
		   }
		   
//		   txtResult.setText(msg.toString());
		   
		   todoItems.add(msg.toString());
           aa.notifyDataSetChanged();

		   } catch(Exception e) {
		    Log.e("파싱 중 에러 발생", e.getMessage());
		   }
		  }
		 
		 
		 Handler handler1 = new Handler() {
	    		public void handleMessage(Message msg) {
	    			downXml();
	    			handler1.sendEmptyMessageDelayed(0, 3000);
	    		}
	    		};
		 
		 private String SendByHttp(String msg) {
				if(msg == null)
					msg = "";
				
				String URL = "http://godling2.cafe24.com/chat/index.php/room/msg/name/ParkYoonsung/data/";
				
				DefaultHttpClient client = new DefaultHttpClient();
				try {
					/* 체크할 id와 pwd값 서버로 전송 */
					HttpGet post = new HttpGet(URL+msg);

					/* 지연시간 최대 5초 */
					HttpParams params = client.getParams();
					HttpConnectionParams.setConnectionTimeout(params, 3000);
					HttpConnectionParams.setSoTimeout(params, 3000);

					/* 데이터 보낸 뒤 서버에서 데이터를 받아오는 과정 */
					HttpResponse response = client.execute(post);
					BufferedReader bufreader = new BufferedReader(
							new InputStreamReader(response.getEntity().getContent(),
									"utf-8"));

					String line = null;
					String result = "";

					while ((line = bufreader.readLine()) != null) {
						result += line;
					}
					
					return result;
				} catch (Exception e) {
					e.printStackTrace();
					client.getConnectionManager().shutdown();	// 연결 지연 종료
					return ""; 
				}
				
			}
		        
		}